#include "freehandcapturewidget.h"
#include "freehandsnapgraphicsscene.h"
#include "src/utils/screengrabber.h"
#include "src/core/capturerequest.h"
#include "src/utils/screenshotsaver.h"
#include <QMouseEvent>
#include <QPainter>

FreeHandCaptureWidget::FreeHandCaptureWidget(QWidget *parent) : QDialog(parent) {
    setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
    setWindowState(Qt::WindowActive);

    setMouseTracking(true);
    graphicsView = new QGraphicsView(this);
    graphicsView->setMouseTracking(true);
    graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    
    bool ok;
    fullScreenPixmap = ScreenGrabber().grabEntireDesktop(ok);
    scene = new FreeHandSnapGraphicsScene(graphicsView);
    scene->setSceneRect(QRectF(0, 0, fullScreenPixmap.width(), fullScreenPixmap.height()));
    scene->setBackgroundBrush(QBrush(fullScreenPixmap));
    
    graphicsView->setRenderHint(QPainter::Antialiasing);
    graphicsView->setScene(scene);
    graphicsView->setGeometry(0, 0, fullScreenPixmap.width(), fullScreenPixmap.height());
}

void FreeHandCaptureWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape) {
        close();
    } else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
        QRectF r = scene->getPathRect();
        QImage image(r.width(), r.height(), QImage::Format_ARGB32_Premultiplied);
        QPainter painter(&image);
        image.fill(Qt::transparent);
        painter.setBrush(QBrush(fullScreenPixmap));
        painter.setPen(QPen(Qt::transparent));
        painter.translate(-r.x(), -r.y());
        painter.drawConvexPolygon(scene->getPathPolygonF());
        // emit captured(CaptureRequest::POLYGON_MODE, QPixmap::fromImage(image));
        // tmp save method
        ScreenshotSaver().saveToFilesystemGUI(QPixmap::fromImage(image), "png");
        close();
    }
}